package com.sinosoft.gateway.event;

import com.sinosoft.gateway.zuul.CustomRouteLocator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.RoutesRefreshedEvent;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * Created by xujingfeng on 2017/4/1.
 */
@Service
@EnableScheduling
public class RefreshRouteService {

    @Autowired
    ApplicationEventPublisher publisher;

    @Autowired
    RouteLocator routeLocator;

    /**
     * 60秒执行一次, 到数据库读取最新的路由配置, 定时触发路由更新监听器, 让它
     * 使用我们自定义的路由加载器{@link CustomRouteLocator}去更新
     */
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void refreshRoute() {
        RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(routeLocator);
        publisher.publishEvent(routesRefreshedEvent);
    }

}
